package com.hulk.dryad.manage.framework.logstash.appender;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.util.JacksonUtil;
import com.hulk.dryad.manage.framework.logstash.config.LoggingLogstashProperties;
import com.hulk.dryad.manage.framework.logstash.util.LogStashUtil;
import lombok.extern.slf4j.Slf4j;


import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * LogStash 输出 json
 *
 * @author hulk
 */
@Slf4j
public class LoggingLogStashAppender implements ILoggingAppender {
	private static final String ASYNC_LOG_STASH_APPENDER_NAME = "ASYNC_LOG_STASH";
	private final LoggingLogstashProperties properties;
	private final String customFieldsJson;

	public LoggingLogStashAppender(Environment environment,
								   LoggingLogstashProperties properties) {
		this.properties = properties;
		// 1. 服务名和环境和日志目录
		String appName = environment.getRequiredProperty(CommonConstants.SPRING_APP_NAME_KEY);
		String profile = environment.getRequiredProperty(CommonConstants.ACTIVE_PROFILES_PROPERTY);
		// 2. json 自定义字段
		Map<String, Object> customFields = new HashMap<>();
		customFields.put("appName", appName);
		customFields.put("profile", profile);
		this.customFieldsJson = JacksonUtil.toJson(customFields);
		LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
		this.start(context);
	}

	@Override
	public void start(LoggerContext context) {
		log.info("LogStash logging start.");
		reload(context);
	}

	@Override
	public void reset(LoggerContext context) {
		log.info("LogStash logging reset.");
		reload(context);
	}

	private void reload(LoggerContext context) {
		LoggingLogstashProperties logStash = properties;
		if (logStash.isEnabled()) {
			addLogStashTcpSocketAppender(context, customFieldsJson, logStash);
		}
	}

	/**
	 * addLogstashTcpSocketAppender.
	 *
	 * @param context            a {@link LoggerContext} object.
	 * @param customFields       a {@link String} object.
	 * @param logStashPropertiesLogback a {@link LoggingLogstashProperties} object.
	 */
	public static void addLogStashTcpSocketAppender(LoggerContext context,
													String customFields,
													LoggingLogstashProperties logStashPropertiesLogback) {
		// More documentation is available at: https://github.com/logstash/logstash-logback-encoder
		final LogstashTcpSocketAppender logStashAppender = new LogstashTcpSocketAppender();
		logStashAppender.addDestinations(new InetSocketAddress(logStashPropertiesLogback.getHost(), logStashPropertiesLogback.getPort()));
		logStashAppender.setContext(context);
		logStashAppender.setEncoder(logstashEncoder(customFields));
		logStashAppender.setName(ASYNC_LOG_STASH_APPENDER_NAME);
		logStashAppender.setQueueSize(logStashPropertiesLogback.getQueueSize());
		logStashAppender.start();
		// 先删除，再添加
		context.getLogger(Logger.ROOT_LOGGER_NAME).detachAppender(ASYNC_LOG_STASH_APPENDER_NAME);
		context.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(logStashAppender);
	}

	private static LogstashEncoder logstashEncoder(String customFields) {
		final LogstashEncoder logstashEncoder = new LogstashEncoder();
		logstashEncoder.setThrowableConverter(LogStashUtil.throwableConverter());
		logstashEncoder.setCustomFields(customFields);
		return logstashEncoder;
	}

}
